var map;
var markerss;
var toolBar;
var points;//轨迹路径
var progress=0;//播放进度
var speed=1000;//播放速度(km/h)
var playIndex=0;//用于标识手动进行修改的播放进度(该变量用于设置播放过的轨迹)
var passedPolyline;//播放过的轨迹路径
var isPlaying=false;//是否正在播放
var satellite='';

function initialize() {
	map = new AMap.Map("container", {
		mapStyle: 'amap://styles/light', 
		center: [116.397428, 39.90923], //创建中心点坐标
		zoom: 5, //设置地图缩放级别
		// zooms:[5,18],
		viewMode:'3D'//使用3D视图
	}); //创建地图实例
	//加载标尺  
	map.plugin(["AMap.Scale"], function() {
		var scale = new AMap.Scale();
		map.addControl(scale);
	});
	map.plugin(["AMap.ToolBar"], function() {
		toolBar = new AMap.ToolBar();
		map.addControl(toolBar);
	});
	satellite = new AMap.TileLayer.Satellite();
    map.addLayer(satellite);
	satellite.hide();
}
//加载轨迹路径
function newLoadPath(pathParam,sign){
	points = [];
	// console.log(newPath);
	for(var i =0,len=pathParam.length;i<len;i+=1){
	  points.push([pathParam[i].longitude,pathParam[i].latitude])
	}
	let strokeColor="#1BAC2E";
	if(sign=='first'){
		map.clearMap(); //每次加载路线时,清除地图上所有覆盖物,防止覆盖物重复
		drawStartAndEndICO(); //绘制起点和终点图标  
	}else{
		strokeColor="#0766FE";
	}
	//绘制轨迹  
	var polyline = new AMap.Polyline({
		map: map,
		path: points,       
		strokeColor: strokeColor,//线颜色
		strokeOpacity: 1,//线透明度
		strokeWeight: 7,//线宽
		strokeDasharray:[10,5],
		position:true,
		lineJoin: 'round',
		showDir:true,
		strokeStyle: "solid"//线样式
		
	});
	var markers=[];
	markers.forEach(function(value) {
		new AMap.Marker({
			map: map,
			icon: value.icon,
			position: [value.position[0], value.position[1]],
			offset: new AMap.Pixel(-22, -40), //相对于基点的位置
		});
	});
	sign=='first'&&map.setFitView();
	//加载gps点
	showGps(pathParam,sign);
	map.on('click', function(ev) {
	  // 触发事件的地理坐标，AMap.LngLat 类型
	  var lnglat = ev.lnglat;
	  // console.log(ev);
	  myControl.checkedPoint.longitude=lnglat.lng;
	  myControl.checkedPoint.latitude=lnglat.lat;
	});
}
var circleMarkerObj={};
function showGps (pathParam,sign) {
	//黄色 ede321    绿色 2ad636    红色 f16747   蓝色 4958e1
	pathParam.forEach((val,key)=>{
		let strokeColor="#ede321";
		strokeColor=val.source==3?'#f16747':'#ede321'
		if(sign!='first'){
			strokeColor="#2ad636"
		}
		var circleMarker = new AMap.CircleMarker({
			center:new AMap.LngLat(val.longitude,val.latitude),
			radius:3,//3D视图下，CircleMarker半径不要超过64px
			zIndex:100,
			cursor:'pointer',
			fillOpacity : 1,
			strokeColor:strokeColor,
			fillColor:strokeColor,
			extData:val
		})
		circleMarkerObj["v"+val.id]=circleMarker;
		circleMarker.setMap(map)
		circleMarker.on('click',(e)=>{
			var extData=e.target._opts.extData;
			console.log(extData)
			myControl.checkedRoutePoint=extData;
			if(myControl.drivingVisible){
				if(myControl.drivingRadio=='开始点'){
					myControl.drivingData.startData=extData;
				}else{
					myControl.drivingData.endData=extData;
				}
			}
		})
		circleMarker.on('dblclick',(e)=>{
			console.log(e);
			var extData=e.target._opts.extData;
			//创建信息窗口  
			var content=`<div class="info_box">
						  <p>`+extData.deviceTime+`</p>
						  <p>速度：`+extData.gpsSpeed+`km/h</p>
					  </div>`;
			var infoWindow = new AMap.InfoWindow({
				// isCustom: true,  //使用自定义窗体
				content: content,
				offset: new AMap.Pixel(-1, -10)
			});
			//打开信息窗口
			infoWindow.open(map, e.lnglat); //后面的参数指的是经纬度，在此显示窗口
		})
	}) 
}
//高德地图规划路线
function aMapDriving(pathParam){
	AMap.plugin('AMap.Driving', function() {
		var driving = new AMap.Driving({
			// 驾车路线规划策略，AMap.DrivingPolicy.LEAST_TIME是最快捷模式
			policy: AMap.DrivingPolicy.LEAST_TIME
		})
		var len=pathParam.length;
		var startLngLat = [pathParam[0].longitude, pathParam[0].latitude]
		var endLngLat = [pathParam[len-1].longitude, pathParam[len-1].latitude]
		driving.search(startLngLat, endLngLat, function (status, result) {
			// 未出错时，result即是对应的路线规划方案
			// console.log(result.routes[0].steps)
			let steps=result.routes[0].steps;
			var points = [];
			// console.log(steps);
			steps.forEach((val,key)=>{
				console.log(val)
				val.path.forEach((value,index)=>{
					points.push([value.lng,value.lat])
				});
			});
			// console.log(points);
			//绘制轨迹
			var polyline = new AMap.Polyline({
				map: map,
				path: points,       
				strokeColor: '#e4393c',//线颜色
				strokeOpacity: 1,//线透明度
				strokeWeight: 9,//线宽
				strokeDasharray:[10,5],
				position:true,
				lineJoin: 'round',
				showDir:true,
				strokeStyle: "solid"//线样式 
			});
			let checkedRoutePoint=pathParam[0];
			points.forEach((val,key)=>{
				let checkedPoint={
					latitude:val[1],
					longitude:val[0],
					operateType:0
				}
				myControl.editPointData.gpsData.push(checkedRoutePoint,checkedPoint);
			})
			console.log(myControl.editPointData.gpsData);
			myControl.operateGpsList();
		})
	})
}
//增加gps点   
function addGpsPoint(){
	let lng = myControl.checkedPoint.longitude;
	let lat = myControl.checkedPoint.latitude;
	var circleMarker = new AMap.CircleMarker({
		center:new AMap.LngLat(lng,lat),
		radius:5,//3D视图下，CircleMarker半径不要超过64px
		zIndex:100,
		cursor:'pointer',
		fillOpacity : 1,
		strokeColor:'#f16747',
		fillColor:'#f16747',
		// extData:val
	})
	circleMarker.setMap(map)
}
//删除gps点   
function deleteGpsPoint(json,sign){
	if(sign=='delete'){
		json.gpsData.forEach((val,key)=>{
			if(val.id){
				let markerId="v"+val.id;
				circleMarkerObj[markerId].hide();
			}
		})
	}else{
		let markerId="v"+json.gpsData[0].id;
		circleMarkerObj[markerId].setOptions({
			fillOpacity : 0.5
		})
	}
}
function drawStartAndEndICO(){

    var start_xy = points[0];
    var end_xy = points[points.length - 1];

    //起点、终点图标
    var sicon = new AMap.Icon({
        image: "http://cache.amap.com/lbs/static/jsdemo002.png",
        size: new AMap.Size(44, 44),
        imageOffset: new AMap.Pixel(-334, -180)
    });
    var startmarker = new AMap.Marker({
        icon: sicon, //复杂图标
        visible: true,
        position: start_xy,
        map: map,
        offset: {
            x: -16,
            y: -40
        }
    });
    var eicon = new AMap.Icon({
        image: "http://cache.amap.com/lbs/static/jsdemo002.png",
        size: new AMap.Size(44, 44),
        imageOffset: new AMap.Pixel(-334, -134)
    });

    var endmarker = new AMap.Marker({
        icon: eicon, //复杂图标
        visible: true,
        position: end_xy,
        map: map,
        offset: {
            x: -16,
            y: -40
        }
    });
    map.setFitView();
}
